package com.ruoyi.ftrl.service.impl;

import com.ruoyi.ftrl.common.MeasurementMapping;
import com.ruoyi.ftrl.domain.CommunityMeasurement;
import com.ruoyi.ftrl.domain.RealTimeData;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class DataProcessor {

    private final CommunityMappingService communityMappingService;

    public DataProcessor(CommunityMappingService communityMappingService) {
        this.communityMappingService = communityMappingService;
    }

    public List<CommunityMeasurement> processData(List<RealTimeData> realTimeDataList) {
        List<CommunityMeasurement> communityMeasurements = new ArrayList<>();
        Map<String, String> communityMap = communityMappingService.getCommunityMap(); // 获取小区映射关系

        // 遍历实时数据
        for (RealTimeData data : realTimeDataList) {
            String dataItemId = data.getDataItemId(); // 获取 data_item_id
            String[] parts = dataItemId.split("_");
            String communityId = parts[1]; // 获取小区 ID
            String measurementPoint = parts[2]; // 获取测量点位

            // 根据小区 ID 获取小区名称
            String communityName = communityMap.getOrDefault(communityId, "未知小区");

            // 查找或创建小区测量对象
            CommunityMeasurement communityMeasurement = findOrCreateCommunityMeasurement(communityMeasurements, communityName);

            // 使用映射获取测量项的描述
            String measurementDescription = MeasurementMapping.getMeasurementDescription(measurementPoint);

            // 添加测量值
            communityMeasurement.addMeasurement(measurementDescription, data.getValue());
        }

        return communityMeasurements;
    }

    private CommunityMeasurement findOrCreateCommunityMeasurement(List<CommunityMeasurement> communityMeasurements, String communityName) {
        for (CommunityMeasurement cm : communityMeasurements) {
            if (cm.getCommunityName().equals(communityName)) {
                return cm;
            }
        }
        CommunityMeasurement newMeasurement = new CommunityMeasurement(communityName);
        communityMeasurements.add(newMeasurement);
        return newMeasurement;
    }
}